import Base64 from "base-64";
import TIM from "@tencentcloud/chat";
import {
  genTestUserSig
} from "@/debug/GenerateTestUserSig.js";

// 模块级变量存储配置
let sdkAppId;
let currentUserSig;
let currentUserID;

let TUITIM;

// #ifdef H5
import {
  TUICallEvent
} from "tuicall-engine-webrtc";
import {
  TUICallKit,
  TUICallKitServer,
  TUICallType
} from '@tencentcloud/call-uikit-vue';
// #endif

// #ifdef APP
const TUICallKit = uni.requireNativePlugin("TencentCloud-TUICallKit");
const TUICallKitEvent = uni.requireNativePlugin("globalEvent");
// #endif

async function initSDK(user_id) {
  try {
    currentUserID = String(user_id);
    const globalConfig = uni.getStorageSync("globalConfig");

    if (!globalConfig?.trtc) {
      throw new Error("TRTC配置信息缺失");
    }

    const decodeObj = JSON.parse(Base64.decode(globalConfig.trtc));
    sdkAppId = Number(decodeObj.sdkappid);

    if (!sdkAppId || !decodeObj.key) {
      throw new Error("无效的TRTC配置参数");
    }

    const {
      userSig
    } = genTestUserSig(currentUserID, sdkAppId, decodeObj.key);
    currentUserSig = userSig;

    // 初始化TIM实例
    await TIMInit();

    // 平台特定初始化
    // #ifdef H5
    await initH5Environment();
    await H5SetSelfInfo()
    // #endif

    // #ifdef APP
    await initAppEnvironment();
    // #endif

  } catch (error) {
    console.error("SDK初始化失败:", error);
    throw error;
  }
}



async function TIMInit() {
  console.log('初始化TIM实例')
  TUITIM = await TIM.create({
    SDKAppID: sdkAppId
  });

  // 执行登录
  await loginTIM(TUITIM);
}

// H5环境初始化
async function initH5Environment() {
  console.log('H5环境初始化')
  await TUICallKitServer.init({
    userID: currentUserID,
    userSig: currentUserSig,
    SDKAppID: sdkAppId,
  });
  console.log('H5成功')
}



async function H5SetSelfInfo() {
  const userInfo = uni.getStorageSync("userInfo");
  await TUICallKitServer.setSelfInfo({
    nickName: userInfo.realname,
    avatar: userInfo.avatar,
  });


  TUICallKitServer.getTUICallEngineInstance().on(TUICallEvent.ON_CALL_RECEIVED, handInvited);
  // TUICallKitServer.getTUICallEngineInstance().off(TUICallEvent.USER_ENTER, handleUserEnter);

}

function handInvited(e) {
  uni.showToast({
    title: '有待接听电话',
    icon: 'none'
  })

  let path = '';
  // #ifdef H5
  path = 'h5-call';
  // #endif
  // #ifdef APP
  path = 'app-call';
  // #endif

  const url =
    `/pages/message/${path}?status=joinGroup&type=joinGroup&groupID=${e.groupID}&type=${e.callMediaType}&roomID=${e.roomID}&callId=${e.callId}`;

  uni.navigateTo({
    url: url
  })
}


// APP环境初始化
async function initAppEnvironment() {
  loginTUICallKit();

  // 配置通话组件
  // TUICallKit.enableFloatWindow(true);
  TUICallKit.enableVirtualBackground(true);
  TUICallKit.setScreenOrientation(2); // 自动旋转
}

async function loginTIM(TUITIM) {
  TUITIM.login({
    userID: currentUserID,
    userSig: currentUserSig,
    success: () => {
      console.log('TIM登录成功')
    },
    error: (err) => {
      console.error('TIM登录失败:', err);
    }
  })
}

function logout() {
  //退出
}

function loginTUICallKit() {
  TUICallKit.login({
    SDKAppID: sdkAppId,
    userID: currentUserID,
    userSig: currentUserSig,
  }, (res) => {
    if (res.code === 0) {
      console.log('TUICallKit登录成功')
      appSetSelfInfo();
    } else {
      console.error('TUICallKit登录失败:', res.msg);
    }
  });
}

function appSetSelfInfo() {
  const userInfo = uni.getStorageSync("userInfo");
  const options = {
    nickName: userInfo.realname,
    avatar: userInfo.avatar,
  };

  TUICallKit.setSelfInfo(options, (res) => {
    if (res.code === 0) {
      console.log("设置用户信息成功");

    } else {
      console.log(`setSelfInfo failed, error message = ${res.msg}`);
    }
  });
}

export {
  sdkAppId,
  currentUserSig,
  initSDK,
  TIM,
  TUITIM,
  TUICallKit,

  // APP导出
  // #ifdef APP
  TUICallKitEvent,
  // #endif

  // H5导出
  // #ifdef H5
  TUICallKitServer,
  TUICallType
  // #endif
}